<template>
  <base-table-layout
    title="农户信息管理"
    :total="total"
    :current-page="currentPage"
    :page-size="pageSize"
    @update:currentPage="val => currentPage = val"
    @update:pageSize="val => pageSize = val"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
    <!-- 搜索区域 -->
    <template #search>
      <el-input
        v-model="searchForm.growerName"
        placeholder="农户姓名"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleSearch"
      />
      <el-select
        v-model="searchForm.belongStation"
        placeholder="所属烟站"
        clearable
        style="width: 200px"
        class="filter-item"
        @change="handleStationChange"
      >
        <el-option
          v-for="item in stationOptions"
          :key="item.deptId"
          :label="item.deptName"
          :value="item.deptId"
        />
      </el-select>
      <el-select
        v-model="searchForm.belongTown"
        placeholder="所属乡镇"
        clearable
        style="width: 200px"
        class="filter-item"
        @change="handleTownChange"
      >
        <el-option
          v-for="item in townOptions"
          :key="item.deptId"
          :label="item.deptName"
          :value="item.deptId"
        />
      </el-select>
      <el-select
        v-model="searchForm.belongGroup"
        placeholder="所属乡村组"
        clearable
        style="width: 200px"
        class="filter-item"
      >
        <el-option
          v-for="item in groupOptions"
          :key="item.deptId"
          :label="item.deptName"
          :value="item.deptId"
        />
      </el-select>
      <el-input
        v-model="searchForm.idCard"
        placeholder="身份证号"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleSearch"
      />
      <el-button
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        搜索
      </el-button>
      <el-button
        icon="el-icon-refresh"
        @click="resetSearch"
      >
        重置
      </el-button>
    </template>

    <!-- 操作区域 -->
    <template #operation>
      <el-button
        type="success"
        icon="el-icon-plus"
        @click="handleAdd"
      >
        新增农户
      </el-button>
      <el-button
        type="primary"
        icon="el-icon-download"
        @click="downloadTemplate"
      >
        下载模板
      </el-button>
      <el-button
        type="primary"
        icon="el-icon-upload2"
        @click="handleImport"
      >
        导入Excel
      </el-button>
      <el-button
        type="primary"
        icon="el-icon-download"
        @click="handleExport"
      >
        导出数据
      </el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column
          prop="growerName"
          label="农户姓名"
          width="120"
        />
        <el-table-column
          prop="belongStation"
          label="所属烟站"
          width="150"
        />
        <el-table-column
          prop="belongTown"
          label="所属乡镇"
          width="150"
        />
        <el-table-column
          prop="belongGroup"
          label="所属组"
          width="180"
        />
        <el-table-column
          prop="address"
          label="详细地址"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="phone"
          label="联系电话"
          width="120"
        />
        <el-table-column
          prop="idCard"
          label="身份证号"
          width="180"
        />
        <el-table-column
          label="开户银行"
          width="150"
        >
          <template slot-scope="scope">
            <template v-if="scope.row.bankType">
              {{ scope.row.bankType }}
              <el-tag v-if="scope.row.bankType && scope.row.bankAccount" size="mini" type="success">默认</el-tag>
            </template>
            <template v-else>
              <el-button type="text" @click.stop="handleBankAccountClick(scope.row)">
                添加银行卡
              </el-button>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          label="银行账号"
          width="220"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.bankAccount" style="cursor: pointer;" @click="handleBankAccountClick(scope.row)">
              {{ scope.row.bankAccount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180"
          fixed="right"
        >
          <template slot-scope="scope">
            <template v-if="showSelect">
              <el-button
                size="mini"
                type="primary"
                @click.stop="handleSelect(scope.row)"
              >选择</el-button>
            </template>
            <template v-else>
              <el-button
                size="mini"
                @click="handleEdit(scope.row)"
              >编辑</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="600px"
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="农户姓名" prop="growerName">
            <el-input v-model="form.growerName" />
          </el-form-item>
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="form.idCard" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" />
          </el-form-item>
          <el-form-item label="所属烟站" prop="belongStation">
            <el-select
              v-model="form.belongStation"
              placeholder="请选择烟站"
              style="width: 100%"
              @change="handleFormStationChange"
            >
              <el-option
                v-for="item in stationOptions"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属乡镇" prop="belongTown">
            <el-select
              v-model="form.belongTown"
              placeholder="请选择乡镇"
              style="width: 100%"
              @change="handleFormTownChange"
            >
              <el-option
                v-for="item in formTownOptions"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属组" prop="belongGroup">
            <el-select
              v-model="form.belongGroup"
              placeholder="请选择乡村组"
              style="width: 100%"
            >
              <el-option
                v-for="item in formGroupOptions"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input
              v-model="form.address"
              type="textarea"
              :rows="2"
            />
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 银行卡管理对话框 -->
      <el-dialog
        title="银行卡管理"
        :visible.sync="bankAccountDialogVisible"
        width="600px"
      >
        <div v-if="currentGrower">
          <h3>{{ currentGrower.growerName }} 的银行卡</h3>
          
          <!-- 新增银行卡表单 -->
          <el-form
            ref="bankAccountForm"
            :model="newBankAccountForm"
            :rules="bankAccountRules"
            label-width="100px"
            style="margin: 20px 0"
          >
            <el-form-item label="开户银行" prop="bankType">
              <el-select
                v-model="newBankAccountForm.bankType"
                placeholder="请选择或输入开户银行"
                style="width: 100%"
                filterable
                allow-create
                default-first-option
              >
                <el-option label="云南农信" value="云南农信" />
                <el-option label="中国农业银行" value="中国农业银行" />
                <el-option label="中国建设银行" value="中国建设银行" />
                <el-option label="中国工商银行" value="中国工商银行" />
                <el-option label="中国银行" value="中国银行" />
                <el-option label="中国邮政储蓄银行" value="中国邮政储蓄银行" />
                <el-option label="交通银行" value="交通银行" />
                <el-option label="招商银行" value="招商银行" />
              </el-select>
            </el-form-item>
            <el-form-item label="银行账号" prop="accountNo">
              <el-input v-model="newBankAccountForm.accountNo" />
            </el-form-item>
            <el-form-item label="设为默认">
              <el-switch v-model="newBankAccountForm.isDefault" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addBankAccount">添加银行卡</el-button>
            </el-form-item>
          </el-form>

          <!-- 银行卡列表 -->
          <el-table :data="bankAccounts" border style="width: 100%">
            <el-table-column prop="bankType" label="开户银行" width="150" />
            <el-table-column prop="accountNo" label="银行账号" min-width="180" />
            <el-table-column label="操作" width="150" align="center">
              <template slot-scope="scope">
                <el-button
                  v-if="!scope.row.isDefault"
                  type="text"
                  @click="setDefaultBankAccount(scope.row.accountId)"
                >
                  设为默认
                </el-button>
                <el-tag v-else size="mini" type="success">默认</el-tag>
                <el-button
                  type="text"
                  style="color: #f56c6c"
                  @click="deleteBankAccount(scope.row.accountId)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-dialog>

      <!-- Excel导入预览对话框 -->
      <el-dialog
        title="导入预览"
        :visible.sync="importDialogVisible"
        width="80%"
        :close-on-click-modal="false"
      >
        <div v-loading="uploadLoading">
          <el-alert
            v-if="importData.length === 0"
            title="未检测到有效数据"
            type="warning"
            :closable="false"
            show-icon
          />
          
          <!-- 添加进度条 -->
          <div v-if="importing" class="import-progress">
            <el-progress 
              :percentage="importProgress" 
              :format="format"
              status="success">
            </el-progress>
            <div class="progress-text">正在导入第 {{ currentImportIndex + 1 }} 条，共 {{ totalImportCount }} 条</div>
          </div>
          
          <el-table
            v-else
            :data="importData"
            border
            style="width: 100%"
            max-height="500"
          >
            <el-table-column
              prop="growerName"
              label="农户姓名"
              width="120"
            />
            <el-table-column
              prop="address"
              label="家庭住址"
              min-width="200"
              show-overflow-tooltip
            />
            <el-table-column
              prop="idCard"
              label="身份证号"
              width="180"
            />
            <el-table-column
              prop="phone"
              label="手机号"
              width="120"
            />
            <el-table-column
              prop="belongGroup"
              label="乡村组"
              width="180"
            />
            <el-table-column
              label="状态"
              width="120"
            >
              <template slot-scope="scope">
                <el-tag
                  :type="validateRow(scope.row) ? 'success' : 'danger'"
                >
                  {{ validateRow(scope.row) ? '有效' : '无效' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          
          <div style="margin-top: 20px">
            <el-button @click="importDialogVisible = false">取 消</el-button>
            <el-button
              type="primary"
              :disabled="!hasValidData"
              @click="confirmImport"
            >
              确认导入
            </el-button>
          </div>
        </div>
      </el-dialog>
    </template>
  </base-table-layout>
</template>

<script>
import BaseTableLayout from '@/components/BaseTableLayout.vue'
import request from '@/utils/request'
import * as XLSX from 'xlsx'

export default {
  name: 'GrowerManagement',
  components: {
    BaseTableLayout
  },
  props: {
    showSelect: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      searchForm: {
        growerName: '',
        idCard: '',
        phone: '',
        deptId: undefined
      },
      stationOptions: [],
      townOptions: [],
      groupOptions: [],
      formTownOptions: [],
      formGroupOptions: [],
      dialogVisible: false,
      dialogTitle: '',
      form: {
        growerId: undefined,
        growerName: '',
        idCard: '',
        phone: '',
        address: '',
        belongStation: '',
        belongTown: '',
        belongGroup: '',
        deptId: '',
        bankType: '',
        bankAccount: ''
      },
      rules: {
        growerName: [{ required: true, message: '请输入农户姓名', trigger: 'blur' }],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        belongStation: [{ required: true, message: '请选择所属烟站', trigger: 'change' }],
        belongTown: [{ required: true, message: '请选择所属乡镇', trigger: 'change' }],
        belongGroup: [{ required: true, message: '请选择所属组', trigger: 'change' }],
        bankAccount: [{ pattern: /^\d{16,19}$/, message: '请输入正确的银行账号', trigger: 'blur' }]
      },
      deptTree: [],
      bankAccountDialogVisible: false,
      currentGrower: null,
      bankAccounts: [],
      newBankAccountForm: {
        growerId: null,
        bankType: '',
        accountNo: '',
        isDefault: false
      },
      bankAccountRules: {
        bankType: [
          { required: true, message: '请选择开户银行', trigger: 'change' }
        ],
        accountNo: [
          { required: true, message: '请输入银行账号', trigger: 'blur' },
          { pattern: /^\d{16,19}$/, message: '银行账号应为16-19位数字', trigger: 'blur' }
        ]
      },
      importDialogVisible: false,
      importData: [],
      uploadLoading: false,
      importing: false,
      importProgress: 0,
      currentImportIndex: 0,
      totalImportCount: 0
    }
  },
  async created() {
    try {
      await this.fetchStations()
      await this.fetchList()
    } catch (error) {
      console.error('初始化数据失败:', error)
    }
  },
  computed: {
    hasValidData() {
      return this.importData.some(this.validateRow)
    }
  },
  methods: {
    async fetchStations() {
      try {
        const response = await request.get('/departments/tree')
        // response中的data字段就是部门树数据
        this.deptTree = response
        // 过滤出烟站列表
        this.stationOptions = response[0].children.filter(item => item.deptType === 1)
      } catch (error) {
        console.error('获取烟站列表失败:', error)
        this.$message.error('获取烟站列表失败')
      }
    },
    async fetchList() {
      try {
        this.loading = true
        // 构造查询参数
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          growerName: this.searchForm.growerName,
          idCard: this.searchForm.idCard,
          phone: this.searchForm.phone
        }

        // 如果选择了乡村组，使用乡村组ID作为deptId
        if (this.searchForm.belongGroup) {
          params.deptId = this.searchForm.belongGroup
        }
        // 如果选择了乡镇，使用乡镇ID作为deptId
        else if (this.searchForm.belongTown) {
          params.deptId = this.searchForm.belongTown
        }
        // 如果只选择了烟站，使用烟站ID作为deptId
        else if (this.searchForm.belongStation) {
          params.deptId = this.searchForm.belongStation
        }
        const response = await request.get('/growers/page', { params })

        // 处理农户数据
        this.tableData = response.records.map(grower => {
          const result = { ...grower }
          
          if (grower.deptId && this.deptTree?.[0]) {
            
            for (const station of this.deptTree[0].children) {
              if (station.deptType === 1) {
                if (station.children) {
                  for (const town of station.children) {
                    if (town.deptType === 2) {
                      if (town.children) {
                        for (const group of town.children) {
                          if (group.deptType === 3 && group.deptId === grower.deptId) {
                            result.belongGroup = group.deptName
                            result.belongTown = town.deptName
                            result.belongStation = station.deptName
                            break
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
          
          return result
        })

        // 获取每个农户的银行卡信息
        await Promise.all(
          this.tableData.map(async grower => {
            try {
              const bankAccounts = await request.get(`/bank-accounts/grower/${grower.growerId}`)
              if (bankAccounts && bankAccounts.length > 0) {
                // 查找默认账户
                const defaultAccount = bankAccounts.find(account => account.isDefault)
                if (defaultAccount) {
                  // 直接修改 grower 对象的属性
                  this.$set(grower, 'bankType', defaultAccount.bankType)
                  this.$set(grower, 'bankAccount', defaultAccount.accountNo)
                }
              }
            } catch (error) {
              console.error(`获取农户 ${grower.growerName} 的银行卡信息失败:`, error)
            }
          })
        )
        this.total = response.total
      } catch (error) {
        console.error('获取农户列表失败:', error)
        this.$message.error('获取农户列表失败')
      } finally {
        this.loading = false
      }
    },
    handleStationChange(val) {
      this.searchForm.belongTown = ''
      this.searchForm.belongGroup = ''
      if (val) {
        const station = this.stationOptions.find(item => item.deptId === val)
        this.townOptions = station ? station.children.filter(item => item.deptType === 2) : []
      } else {
        this.townOptions = []
      }
      this.groupOptions = []
    },
    handleTownChange(val) {
      this.searchForm.belongGroup = ''
      if (val) {
        const town = this.townOptions.find(item => item.deptId === val)
        this.groupOptions = town ? town.children.filter(item => item.deptType === 3) : []
      } else {
        this.groupOptions = []
      }
    },
    handleFormStationChange(val) {
      this.form.belongTown = ''
      this.form.belongGroup = ''
      if (val) {
        const station = this.stationOptions.find(item => item.deptId === val)
        this.formTownOptions = station ? station.children.filter(item => item.deptType === 2) : []
      } else {
        this.formTownOptions = []
      }
      this.formGroupOptions = []
    },
    handleFormTownChange(val) {
      this.form.belongGroup = ''
      if (val) {
        const town = this.formTownOptions.find(item => item.deptId === val)
        this.formGroupOptions = town ? town.children.filter(item => item.deptType === 3) : []
      } else {
        this.formGroupOptions = []
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchList()
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchList()
    },
    resetSearch() {
      this.searchForm = {
        growerName: '',
        idCard: '',
        phone: '',
        deptId: undefined
      }
      this.handleSearch()
    },
    handleAdd() {
      this.dialogTitle = '新增农户'
      this.form = {
        growerName: '',
        address: '',
        idCard: '',
        phone: '',
        belongStation: '',
        belongTown: '',
        belongGroup: '',
        deptId: '',
        bankType: '',
        bankAccount: ''
      }
      this.dialogVisible = true
    },
    async handleEdit(row) {
      try {
        const response = await request.get(`/growers/${row.growerId}`)
        console.log('获取到的农户详情:', response)
        
        // 初始化表单数据
        this.form = {
          growerId: response.growerId,
          growerName: response.growerName,
          address: response.address,
          idCard: response.idCard,
          phone: response.phone,
          bankType: response.bankType,
          bankAccount: response.bankAccount,
          deptId: response.deptId
        }
        
        this.dialogTitle = '编辑农户'

        // 根据deptId查找完整的组织架构信息
        if (this.form.deptId && this.deptTree?.[0]) {
          console.log('开始查找组织架构信息, deptId:', this.form.deptId)
          for (const station of this.deptTree[0].children) {
            if (station.deptType === 1) {
              if (station.children) {
                for (const town of station.children) {
                  if (town.deptType === 2) {
                    if (town.children) {
                      for (const group of town.children) {
                        if (group.deptType === 3 && group.deptId === this.form.deptId) {
                          console.log('找到匹配的组织架构:', {
                            station: station.deptName,
                            town: town.deptName,
                            group: group.deptName
                          })
                          
                          // 设置所属烟站
                          this.form.belongStation = station.deptId
                          // 触发加载乡镇选项
                          this.handleFormStationChange(station.deptId)
                          
                          // 设置所属乡镇
                          this.form.belongTown = town.deptId
                          // 触发加载乡村组选项
                          this.handleFormTownChange(town.deptId)
                          
                          // 设置所属乡村组
                          this.form.belongGroup = group.deptId
                          break
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }

        this.dialogVisible = true
      } catch (error) {
        console.error('获取农户详情失败:', error)
        this.$message.error('获取农户详情失败')
      }
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该农户吗？', '提示', {
          type: 'warning'
        })
        await request.delete(`/growers/${row.growerId}`)
        this.$message.success('删除成功')
        this.fetchList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },
    async handleSubmit() {
      try {
        await this.$refs.form.validate()
        
        // 构造提交的数据
        const submitData = {
          growerName: this.form.growerName,
          address: this.form.address,
          idCard: this.form.idCard,
          phone: this.form.phone,
          deptId: this.form.belongGroup || this.form.deptId, // 确保使用正确的deptId
          bankType: this.form.bankType,
          bankAccount: this.form.bankAccount
        }

        console.log('提交的数据:', submitData) // 添加日志

        if (this.form.growerId) {
          // 编辑模式
          submitData.growerId = this.form.growerId
          await request.put('/growers', submitData)
        } else {
          // 新增模式
          await request.post('/growers', submitData)
        }

        this.$message.success(this.form.growerId ? '更新成功' : '添加成功')
        this.dialogVisible = false
        this.fetchList()
      } catch (error) {
        if (error !== false) {
          console.error('保存失败:', error)
          this.$message.error('保存失败')
        }
      }
    },
    handleImport() {
      if (!this.searchForm.belongStation || !this.searchForm.belongTown) {
        this.$message.warning('请先选择烟站和乡镇')
        return
      }

      // 创建一个隐藏的文件输入框
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = '.xlsx,.xls'
      input.onchange = e => {
        const file = e.target.files[0]
        if (!file) return
        
        this.uploadLoading = true
        
        // 读取Excel文件
        const reader = new FileReader()
        reader.onload = e => {
          try {
            const data = new Uint8Array(e.target.result)
            const workbook = XLSX.read(data, { type: 'array' })
            const firstSheetName = workbook.SheetNames[0]
            const worksheet = workbook.Sheets[firstSheetName]
            
            // 将Excel数据转换为JSON
            const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
            
            // 移除表头
            jsonData.shift()
            
            // 处理数据
            this.importData = jsonData
              .filter(row => row && row.length >= 5) // 确保基本数据完整
              .map(row => ({
                growerName: row[0]? row[0].toString().trim() : '',
                address: row[1]? row[1].toString().trim() : '',
                idCard: row[2]? row[2].toString().trim() : '',
                phone: row[3]? row[3].toString().trim() : '',
                belongGroup: row[4]? row[4].toString().trim() : '',
                bankType: row[5]? row[5].toString().trim() : '',
                bankAccount: row[6]? row[6].toString().trim() : ''
              }))
              .filter(item => item.growerName) // 过滤掉空行
            
            this.importDialogVisible = true
          } catch (error) {
            console.error('解析Excel失败:', error)
            this.$message.error('解析Excel失败，请检查文件格式')
          } finally {
            this.uploadLoading = false
          }
        }
        reader.onerror = () => {
          this.$message.error('读取文件失败')
          this.uploadLoading = false
        }
        reader.readAsArrayBuffer(file)
      }
      input.click()
    },
    async handleExport() {
      try {
        // 构造查询参数，参照fetchList方法的逻辑
        const params = {
          pageSize: 10000,  // 设置较大的数值
          pageNum: 1,
          growerName: this.searchForm.growerName,
          idCard: this.searchForm.idCard,
          phone: this.searchForm.phone
        }
        
        // 如果选择了乡村组，使用乡村组ID作为deptId
        if (this.searchForm.belongGroup) {
          params.deptId = this.searchForm.belongGroup
        }
        // 如果选择了乡镇，使用乡镇ID作为deptId
        else if (this.searchForm.belongTown) {
          params.deptId = this.searchForm.belongTown
        }
        // 如果只选择了烟站，使用烟站ID作为deptId
        else if (this.searchForm.belongStation) {
          params.deptId = this.searchForm.belongStation
        }
        
        const response = await request.get('/growers/page', { params })
        if (!response.records || response.records.length === 0) {
          this.$message.warning('没有数据可导出')
          return
        }

        // 获取所有农户的部门ID和身份证号
        const deptIds = [...new Set(response.records.map(item => item.deptId))]
        
        // 批量获取部门信息
        const deptResponse = await request.post('/departments/batch', deptIds)
        const deptMap = new Map(deptResponse.map(dept => [dept.deptId, dept.deptName]))
        
        // 批量获取银行卡信息
        // const bankAccountsPromises = response.records.map(grower => 
        //   request.get(`/bank-accounts/grower/${grower.growerId}`)
        //     .then(accounts => [grower.growerId, accounts])
        //     .catch(() => [grower.growerId, []])
        // )
        // const bankAccountsResults = await Promise.all(bankAccountsPromises)
        // const bankAccountsMap = new Map(bankAccountsResults)

        // 准备Excel数据
        const headers = ['农户姓名', '地址', '身份证号', '手机号', '所属村组', '银行类型', '银行账号']
        const data = response.records.map(item => {
          // 获取默认银行卡信息
          // const accounts = bankAccountsMap.get(item.growerId) || []
          // const defaultAccount = accounts.find(acc => acc.isDefault) || accounts[0] || {}
          
          return [
            item.growerName,
            item.address || '',
            item.idCard,
            item.phone,
            deptMap.get(item.deptId) || '',
            // defaultAccount.bankType || '',
            // defaultAccount.accountNo || ''
          ]
        })
        
        // 创建工作簿
        const ws = XLSX.utils.aoa_to_sheet([headers, ...data])
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, '农户信息')
        
        // 生成Excel文件
        const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
        const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        
        // 下载文件
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        const now = new Date()
        const fileName = `农户信息_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}.xlsx`
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(link.href)

        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      }
    },
    async fetchBankAccounts(growerId) {
      try {
        const response = await request.get(`/bank-accounts/grower/${growerId}`)
        this.bankAccounts = response
      } catch (error) {
        console.error('获取银行卡列表失败:', error)
        this.$message.error('获取银行卡列表失败')
      }
    },
    async setDefaultBankAccount(accountId) {
      try {
        await request.put(`/bank-accounts/${accountId}/default`)
        this.$message.success('设置成功')
        // 重新获取银行卡列表
        await this.fetchBankAccounts(this.currentGrower.growerId)
        // 刷新农户列表
        await this.fetchList()
      } catch (error) {
        console.error('设置默认银行卡失败:', error)
        this.$message.error('设置默认银行卡失败')
      }
    },
    async handleBankAccountClick(row) {
      this.currentGrower = row
      this.newBankAccountForm = {
        growerId: row.growerId,
        bankType: '',
        accountNo: '',
        isDefault: false
      }
      await this.fetchBankAccounts(row.growerId)
      this.bankAccountDialogVisible = true
    },

    async addBankAccount() {
      try {
        await this.$refs.bankAccountForm.validate()
        
        const params = {
          growerId: this.newBankAccountForm.growerId,
          bankType: this.newBankAccountForm.bankType,
          accountNo: this.newBankAccountForm.accountNo,
          isDefault: this.newBankAccountForm.isDefault
        }

        await request.post('/bank-accounts', params)
        this.$message.success('添加成功')
        await this.fetchBankAccounts(this.currentGrower.growerId)
        await this.fetchList()
        
        // 重置表单
        this.newBankAccountForm.bankType = ''
        this.newBankAccountForm.accountNo = ''
        this.newBankAccountForm.isDefault = false
      } catch (error) {
        if (error !== false) {
          console.error('添加银行卡失败:', error)
          this.$message.error('添加银行卡失败')
        }
      }
    },

    async deleteBankAccount(accountId) {
      try {
        await this.$confirm('确认删除该银行卡吗？', '提示', {
          type: 'warning'
        })
        await request.delete(`/bank-accounts/${accountId}`)
        this.$message.success('删除成功')
        await this.fetchBankAccounts(this.currentGrower.growerId)
        await this.fetchList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除银行卡失败:', error)
          this.$message.error('删除银行卡失败')
        }
      }
    },
    validateRow(row) {
      // 验证必填字段
      if (!row.growerName || !row.idCard || !row.phone || !row.belongGroup) {
        return false
      }
      
      // 验证身份证号格式
      const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      if (!idCardReg.test(row.idCard)) {
        return false
      }
      
      // 验证手机号格式
      const phoneReg = /^1[3-9]\d{9}$/
      if (!phoneReg.test(row.phone)) {
        return false
      }
      
      return true
    },
    
    format(percentage) {
      return `${percentage}%`
    },
    
    // 休眠函数
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms))
    },
    
    async confirmImport() {
      try {
        const validData = this.importData.filter(this.validateRow)
        if (validData.length === 0) {
          this.$message.warning('没有有效的数据可以导入')
          return
        }

        // 初始化导入进度
        this.importing = true
        this.importProgress = 0
        this.currentImportIndex = 0
        this.totalImportCount = validData.length

        // 获取已存在的乡村组
        const response = await request.get(`/departments/parent/${this.searchForm.belongTown}`)
        const existingGroups = new Map(
          response.filter(dept => dept.deptType === 3)
            .map(dept => [dept.deptName, dept.deptId])
        )

        // 处理每条数据
        for (const [index, item] of validData.entries()) {
          try {
            this.currentImportIndex = index
            this.importProgress = Math.floor((index / validData.length) * 100)
            
            let deptId = existingGroups.get(item.belongGroup)
            let growerId
            
            // 1. 如果乡村组不存在，创建新的乡村组
            if (!deptId) {
              console.log('创建新村组:', item.belongGroup)
              const createResponse = await request.post('/departments', {
                deptName: item.belongGroup,
                parentId: this.searchForm.belongTown,
                deptType: 3
              })
              
              // 保存新创建的乡村组ID到Map中
              deptId = createResponse
              existingGroups.set(item.belongGroup, deptId)
              console.log('新建村组成功，deptId:', deptId)
            }

            // 2. 如果农户不存在，创建新农户
            if (!growerId) {
              const createGrowerResponse = await request.post('/growers', {
                growerName: item.growerName,
                address: item.address,
                idCard: item.idCard,
                phone: item.phone,
                deptId: deptId
              })

              growerId = createGrowerResponse
              console.log('新建农户成功，growerId:', growerId)
            }     

            // 2. 根据身份证号查询农户是否存在
            try {
              const existingGrower = await request.get('/growers/by-idcard', {
                params: { idCard: item.idCard }
              })
              if (existingGrower) {
                growerId = existingGrower.growerId
                console.log('找到已存在的农户:', growerId)
              }
            } catch (error) {
              if (error.response && error.response.status === 404) {
                console.log('农户不存在，将创建新农户')
              } else {
                throw error
              }
            }

            // 4. 如果有银行卡信息，添加银行卡
            if (item.bankType && item.bankAccount) {
              await request.post('/bank-accounts', {
                growerId: growerId,
                bankType: item.bankType,
                accountNo: item.bankAccount,
                isDefault: true // 导入的第一张卡设为默认
              })
              console.log('添加银行卡成功')
            }

            // 每次导入后休息0.5秒
            await this.sleep(500)
          } catch (error) {
            console.error(`导入第 ${index + 1} 条数据失败:`, error)
            this.$message.warning(`导入第 ${index + 1} 条数据失败，继续处理下一条...`)
            continue
          }
        }

        // 完成导入
        this.importProgress = 100
        await this.sleep(500) // 等待进度条显示完成

        this.$message.success('导入完成')
        this.importDialogVisible = false
        this.importing = false
        this.fetchList()
      } catch (error) {
        console.error('导入失败:', error)
        this.$message.error('导入失败')
        this.importing = false
      }
    },
    handleRowClick(row) {
      if (this.showSelect) {
        this.handleSelect(row)
      }
    },
    handleSelect(row) {
      if (!row.userId) {
        this.$emit('select', row)
      } else {
        this.$message.warning('该农户已绑定账号')
      }
    },
    // 下载模板
    downloadTemplate() {
      try {
        // 模板表头
        const headers = ['农户姓名', '地址', '身份证号', '手机号', '乡村组', '银行类型', '银行卡号']
        
        // 示例数据
        const exampleData = [
          ['李楚楚', '云南省临沧市云县茂兰镇净石村委会中心组', '533523197304040552', '18288396896', '中心组', '红塔银行', '623135771120127262']
        ]
        
        // 创建工作簿和工作表
        const ws = XLSX.utils.aoa_to_sheet([headers, ...exampleData])
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, '农户信息模板')
        
        // 设置列宽
        const colWidths = [10, 40, 20, 15, 15, 15, 25]
        ws['!cols'] = colWidths.map(width => ({ width }))
        
        // 生成文件并下载
        const now = new Date()
        const fileName = `农户信息导入模板_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}.xlsx`
        XLSX.writeFile(wb, fileName)
        
        this.$message.success('模板下载成功')
      } catch (error) {
        console.error('下载模板失败:', error)
        this.$message.error('下载模板失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-item {
  margin-right: 8px;
  margin-bottom: 8px;
}

.bank-account-cell {
  .el-tag {
    margin-left: 5px;
  }

}

.el-alert {
  margin-bottom: 20px;
}

.import-progress {
  margin: 20px 0;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;

  .progress-text {
    margin-top: 10px;
    text-align: center;
    color: #606266;
  }
}
</style>

